package com.egao.common.core.log;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 日志工具
 * @author lym
 * @date 2024/8/22 10:27
 */
@Component
public class LogUtils {

    /** 存放路径 */
    private static String dir;

    @Value("${logging.dir}")
    public void setDir(String dir){
        LogUtils.dir = dir;
    }

    private static void record(String level, String category, String message) {
        String name = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        String filePath = StrUtil.format("{}/{}/{}/{}.log", dir, level, category, name);
        FileUtil.touch(filePath);
        FileWriter writer = new FileWriter(filePath);
        writer.appendLines(ListUtil.of("时间：" + DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN)));
        writer.appendLines(ListUtil.of(message));
        writer.appendLines(ListUtil.of("--------------------------------"));
        writer.appendLines(ListUtil.of(""));
    }

    public static void info(String category, String message) {
        record("info", category, message);
    }

    public static void error(String category, String message) {
        record("error", category, message);
    }
}
